﻿using Android;
using Android.App;
using Android.Bluetooth;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Widget;
using AndroidX.AppCompat.App;
using AndroidX.Core.App;
using AndroidX.Core.Content;
using System;
using System.Collections.Generic;

namespace WSYmi.ConnectAct
{
    [Activity(Label = "ConnectActivity")]
    public class ConnectActivity : AppCompatActivity
    {
        private int REQUEST_ENABLE_BT { get; } = 1;

        /// <summary>
        /// 蓝牙适配器
        /// </summary>
        BluetoothAdapter BluetoothAdapter { get; set; }
        /// <summary>
        /// 蓝牙设备
        /// </summary>
        private BluetoothDevice Device { get; set; }
        /// <summary>
        /// ListView定制适配器
        /// </summary>
        public static ConnectAdapter ConnAdapter { get; set; }
        /// <summary>
        /// 扫描到的蓝牙设备信息列表
        /// </summary>
        public static List<MyDevice> DeviceList { get; set; } = new List<MyDevice>();

        private TextView Tv搜索蓝牙页面标题;
        private Button Btn扫描;
        private LinearLayout Ll正在扫描;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Create your application here
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.activity_connect);

            Tv搜索蓝牙页面标题 = FindViewById<TextView>(Resource.Id.Tv搜索蓝牙页面标题);
            Tv搜索蓝牙页面标题.Click += Tv搜索蓝牙页面标题_Click;
            //设置ListView控件
            ListView listView = FindViewById<ListView>(Resource.Id.Ltv蓝牙设备);
            ConnAdapter = new ConnectAdapter(this, DeviceList);
            listView.Adapter = ConnAdapter;
            listView.ItemClick += Ltv蓝牙设备_ItemClick;

            Btn扫描 = FindViewById<Button>(Resource.Id.Btn扫描);
            Btn扫描.Click += OnBtn扫描Click;

            Ll正在扫描 = FindViewById<LinearLayout>(Resource.Id.Ll正在扫描);

            BluetoothManager bluetooth = (GetSystemService(Android.Content.Context.BluetoothService) as BluetoothManager);
            BluetoothAdapter = bluetooth.Adapter;

            //确认打开蓝牙模块，没有请求调用蓝牙权限对话框
            if (BluetoothAdapter == null || !BluetoothAdapter.IsEnabled)
            {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ActionRequestEnable);
                StartActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }

            if (BluetoothAdapter == null)
            {
                Toast.MakeText(Application.Context, "未找到蓝牙模块", ToastLength.Long).Show();
                return;
            }

            List<string> requestList = new List<string>();
            if (Build.VERSION.SdkInt >= BuildVersionCodes.S)
            {
                requestList.Add(Manifest.Permission.BluetoothScan);
                requestList.Add(Manifest.Permission.BluetoothAdvertise);
                requestList.Add(Manifest.Permission.BluetoothConnect);
            }
            else
            {
                requestList.Add(Manifest.Permission.AccessCoarseLocation);
                requestList.Add(Manifest.Permission.AccessFineLocation);
            }

            //获取蓝牙扫描权限
            ActivityCompat.RequestPermissions(this, requestList.ToArray(), REQUEST_ENABLE_BT);

            //蓝牙返回响应过滤
            IntentFilter filter = MakeFilter();
            BluetoothReceiver receiver = new BluetoothReceiver();
            RegisterReceiver(receiver, filter);

            ScanLeDevice();
        }

        /// <summary>
        /// 点击页面标题回到上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Tv搜索蓝牙页面标题_Click(object sender, EventArgs e)
        {
            Finish();
        }

        private Handler Handler { get; set; } = new Handler(Looper.MyLooper());

        private void OnBtn扫描Click(object sender, EventArgs e)
        {
            ScanLeDevice();
        }

        /// <summary>
        /// 蓝牙扫描
        /// </summary>
        /// <param name="enable">是否准许</param>
        private void ScanLeDevice()
        {
            if (BluetoothAdapter.IsDiscovering)
            {
                return;
            }
            _ = Handler.PostDelayed(() =>
            {
                StopScanLeDevice();
            }, 20000);

            IntentFilter filter = MakeFilter();
            BluetoothReceiver receiver = new BluetoothReceiver();
            RegisterReceiver(receiver, filter);
            BluetoothAdapter.StartDiscovery();  //开始发现蓝牙
            Btn扫描.Visibility = Android.Views.ViewStates.Gone;
            Ll正在扫描.Visibility = Android.Views.ViewStates.Visible;
        }

        /// <summary>
        /// 停止蓝牙扫描
        /// </summary>
        private void StopScanLeDevice()
        {
            BluetoothAdapter.CancelDiscovery();

            Ll正在扫描.Visibility = Android.Views.ViewStates.Gone;
            Btn扫描.Visibility = Android.Views.ViewStates.Visible;
        }

        protected override void OnStart()
        {
            base.OnStart();
            DeviceList.Clear();
            ConnAdapter.NotifyDataSetChanged();
        }

        /// <summary>
        ///  蓝牙广播过滤器  蓝牙状态改变  找到设备  搜索完成  开始扫描  状态改变
        /// </summary>
        /// <returns></returns>
        public IntentFilter MakeFilter()
        {
            IntentFilter filter = new IntentFilter();
            filter.AddAction(BluetoothAdapter.ActionStateChanged);//蓝牙状态改变的广播
            filter.AddAction(BluetoothDevice.ActionFound);//找到设备的广播
            filter.AddAction(BluetoothAdapter.ActionDiscoveryFinished);//搜索完成的广播
            filter.AddAction(BluetoothAdapter.ActionDiscoveryStarted);//开始扫描的广播
            filter.AddAction(BluetoothDevice.ActionBondStateChanged);//状态改变
            return filter;
        }

        private void Ltv蓝牙设备_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            StopScanLeDevice();// 停止扫描

            string address = DeviceList[e.Position].Address;
            if (address.Length > 0)
            {
                try
                {
                    Device = BluetoothAdapter.GetRemoteDevice(address);
                    Intent intent = new Intent();
                    intent.PutExtra("Device", Device);
                    intent.PutExtra("Address", address);
                    SetResult(Result.Ok, intent);//返回MainActivity
                }
                catch
                {

                }
                Finish();
            }
        }

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}
